package com.hy.service;


import com.hy.mapper.MedicineOrderMapper;
import com.hy.mapper.OrderItemMapper;

import com.hy.medicine.MedicineOrder;
import com.hy.medicine.OrderItem;
import com.hy.medicine.dingdan.dto.OrderCreateDTO;
import com.hy.medicine.dingdan.dto.OrderItemDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private MedicineOrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    
    private MedicineService medicineService;

    @Override
    @Transactional
    public String createOrder(OrderCreateDTO orderCreateDTO) {
        // 生成订单ID
        String orderId = generateOrderId();

        // 检查所有商品库存
        for (OrderItemDTO item : orderCreateDTO.getOrderItems()) {
            if (!medicineService.checkStock(item.getMedicineId().intValue(), item.getQuantity())) {
                return null; // 库存不足，创建订单失败
            }
        }

        // 创建订单
        MedicineOrder order = new MedicineOrder();
        order.setOrderId(Long.valueOf(orderId));
        order.setUserId(Math.toIntExact(orderCreateDTO.getUserId()));
        order.setReceiverName(orderCreateDTO.getReceiverName());
        order.setReceiverPhone(orderCreateDTO.getReceiverPhone());
        order.setReceiverAddress(orderCreateDTO.getReceiverAddress());
        order.setPaymentType(orderCreateDTO.getPaymentType());
        order.setPaymentName(orderCreateDTO.getPaymentName());
        order.setDeliveryFee(orderCreateDTO.getDeliveryFee());
        order.setTotalAmount(orderCreateDTO.getTotalAmount());
        order.setActualPayment(orderCreateDTO.getActualPayment());
        order.setOrderStatus(0); // 初始状态为待支付
        order.setCreateTime(new Date());

        orderMapper.insert(order);

        // 创建订单项
        List<OrderItem> orderItems = new ArrayList<>();
        for (OrderItemDTO itemDTO : orderCreateDTO.getOrderItems()) {
            OrderItem item = new OrderItem();
            item.setOrderId(orderId);
            item.setMedicineId(itemDTO.getMedicineId());
            item.setMedicineName(itemDTO.getMedicineName());
            item.setImageUrl(itemDTO.getImageUrl());
            item.setSpecification(itemDTO.getSpecification());
            item.setDosageForm(itemDTO.getDosageForm());
            item.setPrice(itemDTO.getPrice());
            item.setQuantity(itemDTO.getQuantity());
            item.setTotalPrice(itemDTO.getPrice().multiply(new BigDecimal(itemDTO.getQuantity())));

            orderItems.add(item);

            // 减少库存
            medicineService.decreaseStock(itemDTO.getMedicineId().intValue(), itemDTO.getQuantity());
        }

        orderItemMapper.batchInsert(orderItems);

        return orderId;
    }

    @Override
    public MedicineOrder getOrderById(String orderId) {
        MedicineOrder order = orderMapper.selectById(orderId);
        if (order != null) {
            // 获取订单项
            List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
            order.setOrderItems(items);
        }
        return order;
    }

    @Override
    public List<MedicineOrder> getOrdersByUserId(Long userId, Integer status) {
        return orderMapper.selectByUserId(userId, status);
    }

    @Override
    public List<OrderItem> getOrderItems(String orderId) {
        return orderItemMapper.selectByOrderId(orderId);
    }

    @Override
    @Transactional
    public boolean cancelOrder(String orderId, Long userId) {
        MedicineOrder order = orderMapper.selectById(orderId);
        if (order == null || !order.getUserId().equals(userId) || order.getOrderStatus() != 0) {
            return false; // 订单不存在、不属于该用户或者状态不是待支付，不能取消
        }

        // 更新订单状态为已取消
        return updateOrderStatus(orderId, 4);
    }

    @Override
    @Transactional
    public boolean payOrder(String orderId, String paymentType) {
        MedicineOrder order = orderMapper.selectById(orderId);
        if (order == null || order.getOrderStatus() != 0) {
            return false; // 订单不存在或者状态不是待支付
        }

        // 更新支付方式（如果需要）
        if (!order.getPaymentType().equals(paymentType)) {
            orderMapper.updatePayment(orderId, paymentType);
        }

        // 更新订单状态为已支付
        return updateOrderStatus(orderId, 1);
    }

    @Override
    public boolean updateOrderStatus(String orderId, Integer status) {
        return orderMapper.updateStatus(orderId, status) > 0;
    }

    /**
     * 生成订单ID
     * @return 订单ID (String类型)
     */
    private String generateOrderId() {
        // 使用UUID的hashCode（确保为正数）
        long uuid = Math.abs(UUID.randomUUID().hashCode());
        // 加上时间戳后6位作为前缀，确保有序性
        long timestamp = System.currentTimeMillis() % 1000000L;
        return timestamp * 10000000L + (uuid % 10000000L) + "";
    }
}
